<style lang="less">
    @import "./agent.less";
</style>

<template>
    <Form ref="userForm" :model="fields" :rules="rules">
        <Row :gutter="16">
            <Col span="8">
            <FormItem label="账号" prop="name">
                <Input v-model="fields.name" placeholder="请输入账号"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="邮箱账号" prop="email">
                <Input v-model="fields.email" placeholder="请输入电子邮箱"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="手机号码" prop="mobile">
                <Input v-model="fields.mobile" placeholder="请输入手机号码" maxlength="11"></Input>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="8">
            <FormItem label="真实姓名" prop="realname">
                <Input v-model="fields.realname" placeholder="请输入真实姓名"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="身份证号码" prop="identity_card">
                <Input v-model="fields.identity_card" maxlength="18" placeholder="请输入18位身份证号码"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="性别" prop="sex">
                <Select v-model="fields.sex">
                    <Option value="0">保密</Option>
                    <Option value="1">男</Option>
                    <Option value="2">女</Option>
                </Select>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="10">
                <FormItem label="省市区" prop="regions">
                    <Cascader :data="regions" trigger="hover" v-model="regionSelected"></Cascader>
                </FormItem>
            </Col>
            <Col span="4">
                <FormItem label="重新获取">
                    <Button icon="loop" :loading="regionLoading" size="middle" @click="getRegions">刷新</Button>
                </FormItem>
            </Col>
            <Col span="10">
                <FormItem label="详细地址" prop="address">
                    <Input v-model="fields.address" placeholder="街道/小区/门牌号"></Input>
                </FormItem>
            </Col>
        </Row>
        <Row :gutter="16" v-if="false">
            <Col span="6">
            <FormItem label="平台分红" prop="prorations">
                <InputNumber :max="100" v-model="fields.prorations.v0">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
            <Col span="6">
            <FormItem label="一级代理分红" prop="prorations">
                <InputNumber :max="100" v-model="fields.prorations.v1">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
            <Col span="6">
            <FormItem label="二级代理分红" prop="prorations">
                <InputNumber :max="100" v-model="fields.prorations.v2">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
            <Col span="6">
            <FormItem label="三级代理分红" prop="prorations">
                <InputNumber :max="100" v-model="fields.prorations.v3">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="24">
            <FormItem :label="prorationSliderLabel" prop="proration">
                <InputNumber :max="100" :min="0" :precision="0" v-model="fields.proration"></InputNumber>
                <span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="12">
            <FormItem label="密码" prop="password">
                <Input type="password" v-model="fields.password" placeholder="请输入密码"></Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="确认密码" prop="re_password">
                <Input type="password" v-model="fields.re_password" placeholder="请再次输入密码"></Input>
            </FormItem>
            </Col>
        </Row>
        <Row>
            <Col>
            <FormItem>
                <Button type="primary" @click="handleSubmit">提交</Button>
                <Button type="ghost" style="margin-left: 10px" @click="handleCancel">取消</Button>
            </FormItem>
            </Col>
        </Row>
    </Form>
</template>

<script>
    import util from '@/libs/util';
    export default {
        data () {
            const validePhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            };
            const valideRePassword = (rule, value, callback) => {
                if (value !== this.fields.password) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            };

            return {
                regionSelected: [],
                regionLoading: false,
                isShowProrations: false,
                prorationSliderLabel: '',
                fields: {
                    name: '',
                    email: '',
                    mobile: '',
                    identity_card: '',
                    realname: '',
                    sex: '0',
                    is_effect: true,
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    address: '',
                    prorations: {
                      v0: '',
                      v1: '',
                      v2: '',
                      v3: ''
                    },
                    proration: 0,
                    real_proration: 0,
                    regions:[],
                    password: '',
                    re_password: '',
                    source: 'backend'
                },

                rules: {
                    name: [
                        { required: true, message: '请输入用户账号', trigger: 'blur'},
                        { type: 'string', min: 2, max: 16, message: '账号格式必须是英文字母、下划线或数字，2~16个字符' }
                    ],
                    email: [
                        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                        { type: 'email', message: '电子邮箱格式错误', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请填写手机号码', trigger: 'blur' },
                        { validator: validePhone }
                    ],
                    proration: [
                        { required: true, type: 'number', message: '请输入分红比例', trigger: 'blur', min: 0, max: 100 }
                    ],
                    identity_card: [
                        { required: true, message: '请输入18位身份证号码', trigger: 'blur', min: 18, max: 18 }
                    ],
                    realname: [
                        { required: true, message: '请输入真实姓名, 2~8个字之间', trigger: 'blur', min: 2, max: 8 }
                    ],
                    regions: [
                        { required: true, type: 'array', message: '请选择省市区', trigger: 'change' }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'blur' }
                    ],
                    address: [
                        { required: true, message: '请输入详细地址', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { type: 'string', min: 6, max: 18, massage: '密码必须6~18个字符', trigger: 'blur' }
                    ],
                    re_password: [
                        { required: true, message: '请再次输入密码', trigger: 'blur' },
                        { validator: valideRePassword, trigger: 'blur' }
                    ]
                }
            }
        },

        watch: {
            regionSelected: function (newVal) {
                this.fields.province_code = newVal[0];
                this.fields.city_code = newVal[1];
                this.fields.district_code = newVal[2];
                this.fields.regions = newVal;
            },

            show: function () {
                this.getDefaultProrations();
                const loginUser = this.$store.state.user.user;
                let userRoles = loginUser.roles_name || [];
                if (util.anyInOf(userRoles, ['admin', 'system'])) {
                    this.isShowProrations = true;
                } else if (util.oneOf('agent', userRoles)) {
                    this.isShowProrations = false;
                }
            },

            'fields.proration': function (proration) {
                this.fields.real_proration = this.realProration(this.$store.state.user.user, proration);

                const loginUser = this.$store.state.user.user;
                if (loginUser.extension == null || loginUser.extension.agent_level < 2) {
                    this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                        + '（ 实际占订单收益[含下一级]：' + this.fields.real_proration+ '% ）';
                } else {
                    this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                        + '（ 实际占订单收益：' + this.fields.real_proration+ '% ）';
                }
            }
        },

        props: {
            rootNode: Object,
            regions: [],
            show: Boolean
        },

        created () {
            this.getDefaultProrations();

            const loginUser = this.$store.state.user.user;
            let userRoles = loginUser.roles_name || [];
            if (util.anyInOf(userRoles, ['admin', 'system'])) {
                this.isShowProrations = true;
            } else if (util.oneOf('agent', userRoles)) {
                this.isShowProrations = false;
            }

            if (loginUser.extension == null || loginUser.extension.agent_level < 2) {
                this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                    + '（ 实际占订单收益[含下一级]：' + this.fields.real_proration+ '% ）';
            } else {
                this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                    + '（ 实际占订单收益：' + this.fields.real_proration+ '% ）';
            }
        },

        methods: {
            handleSubmit () {
                this.$refs.userForm.validate((valid) => {
                    if (valid && this.validatorProrations()) {
                        this.addUser(this.fields);
                    } else {
                        this.$Message.error('验证失败');
                    }
                });
            },

            handleCancel () {
                this.rootNode.addModal = false;
            },

            addUser (data) {
                util.api().post(`/admin/api/agents`, data).then((resp) => {
                    if (resp.data.status == true) {
                        this.$Message.success(resp.data.message);
                        this.rootNode.addModal = false;
                        resp.data.data.balance = 0;
                        this.$emit('on-change', resp.data.data);
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                }).catch((e) => {
                    if (e.response) {
                        if (e.response.status == 422) {
                            if (e.response.data.hasOwnProperty('errors')) {
                                for (let i in e.response.data.errors) {
                                    this.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                                }
                            }
                        } else {
                            this.$Message.error(e.response.data.message);
                        }
                    }  else {
                        this.$Message.error('网络请求异常');
                    }
                })
            },

            getDefaultProrations () {
                util.api().get('/admin/api/configs/system').then((resp) => {
                    if (resp.data.data.hasOwnProperty('prorations')) {
                        this.fields.prorations = resp.data.data.prorations;
                    }
                }).catch((e) => {
                    util.handleApiException(e, this, '获取默认分红比例失败');
                });
            },

            validatorProrations () {
//                if (this.fields.prorations.v0 + this.fields.prorations.v1 + this.fields.prorations.v2 + this.fields.prorations.v3 !== 100) {
//                    this.$Notice.error({ title: '分红比例之和必须等于100%'});
//                    return false;
//                }
                if (this.fields.proration > 100 || this.fields.proration < 0) {
                    this.$Notice.error({ title: '分红比例必须在%1~100%之间'});
                    return false;
                }

                return true;
            },

            getRegions () {
                this.regionLoading = true;
                util.ajax.get('/api/regions/format').then((resp) => {
                    const formatTree = (arr) => {
                        let regions = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].code;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }

                            regions.push(node);
                        }
                        return regions;
                    };

                    this.regions = formatTree(resp.data.data);
                    this.regionLoading = false;
                }).catch((e) => {
                    this.regionLoading = false;
                    util.handleApiException(e, this, '获取省市区数据失败');
                })
            },

            realProration(parent_agent, proration) {
                if (parent_agent.extension == null) {
                    return proration;
                } else if (parent_agent.extension.agent_level == 1) {
                    let _proration = parent_agent.extension.proration * proration / 100;
                    return _proration.toFixed(2);
                } else if (parent_agent.extension.agent_level == 2) {
                    let agent_v2_ratio = parent_agent.extension.parent.extension.proration * parent_agent.extension.proration / 100;
                    let _proration = agent_v2_ratio * proration / 100;
                    return _proration.toFixed(2);
                }

                return proration;
            }
        }
    }
</script>
